// 全局状态
const state = {
    currentUser: null,
    items: []
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initApp();
});

// 初始化应用
async function initApp() {
    await checkLoginStatus();
    setupEventListeners();
    loadItems();
}

// 检查登录状态
async function checkLoginStatus() {
    try {
        const response = await fetch('/api/users/current');
        if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
                state.currentUser = data.data;
                updateUserInterface();
            }
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        alert('登录失败，请重试');
    }
}

// 更新用户界面
function updateUserInterface() {
    const guestButtons = document.getElementById('guestButtons');
    const userInfo = document.getElementById('userInfo');
    
    if (state.currentUser) {
        guestButtons.classList.add('hidden');
        userInfo.classList.remove('hidden');
        userInfo.querySelector('.username').textContent = state.currentUser.username;
    } else {
        guestButtons.classList.remove('hidden');
        userInfo.classList.add('hidden');
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 导航链接
    document.querySelectorAll('[data-page]').forEach(element => {
        element.addEventListener('click', (e) => {
            e.preventDefault();
            showPage(element.dataset.page);
        });
    });

    // 登录表单
    document.getElementById('loginForm').addEventListener('submit', handleLogin);

    // 注册表单
    document.getElementById('registerForm').addEventListener('submit', handleRegister);

    // 发布表单
    document.getElementById('publishForm').addEventListener('submit', handlePublish);

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', handleLogout);

    // 搜索
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');

    // 搜索按钮点击
    searchBtn.addEventListener('click', () => {
        handleSearch();
    });

    // 搜索框回车
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    });
}

// 显示指定页面
function showPage(pageName) {
    // 隐藏所有页面
    document.querySelectorAll('.page').forEach(page => {
        page.classList.add('hidden');
    });
    
    // 显示目标页面
    const targetPage = document.getElementById(pageName + 'Page');
    if (targetPage) {
        targetPage.classList.remove('hidden');
    }
    
    // 更新导航状态
    document.querySelectorAll('.navbar-menu a').forEach(link => {
        if (link) {
            link.classList.remove('active');
            if (link.dataset.page === pageName) {
                link.classList.add('active');
            }
        }
    });
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    
    try {
        const response = await fetch('/api/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(formData))
        });
        
        const data = await response.json();
        if (data.code === 200) {
            state.currentUser = data.data;
            updateUserInterface();
            showPage('home');
            form.reset();
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('登录失败:', error);
        alert('登录失败，请重试');
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    
    try {
        const response = await fetch('/api/users/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(Object.fromEntries(formData))
        });
        
        const data = await response.json();
        if (data.code === 200) {
            alert('注册成功，请登录');
            showPage('login');
            form.reset();
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('注册失败:', error);
        alert('注册失败，请重试');
    }
}

// 处理发布
async function handlePublish(e) {
    e.preventDefault();
    const form = e.target;
    const formData = new FormData(form);
    
    try {
        // 先上传图片
        const imageFile = formData.get('image');
        let imageUrl = '';
        
        if (imageFile && imageFile.size > 0) {
            const imageFormData = new FormData();
            imageFormData.append('file', imageFile);
            
            const uploadResponse = await fetch('/api/upload', {
                method: 'POST',
                body: imageFormData
            });
            
            const uploadData = await uploadResponse.json();
            if (uploadData.code === 200) {
                imageUrl = uploadData.data.url;
            } else {
                alert('图片上传失败：' + uploadData.message);
                return;
            }
        }
        
        // 发布物品信息
        const itemData = {
            name: formData.get('name'),
            description: formData.get('description'),
            location: formData.get('location'),
            status: formData.get('status'),
            image: imageUrl
        };
        
        const response = await fetch('/api/items', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(itemData)
        });
        
        const data = await response.json();
        if (data.code === 200) {
            alert('发布成功');
            await loadItems();
            showPage(itemData.status === 'LOST' ? 'lost' : 'found');
            
            // 重置表单和图片预览
            form.reset();
            const imagePreview = document.getElementById('imagePreview');
            const fileName = document.getElementById('fileName');
            imagePreview.style.display = 'none';
            imagePreview.innerHTML = '';
            fileName.textContent = '';
            
            // 重置文件输入框
            const imageInput = document.getElementById('imageInput');
            imageInput.value = '';
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('发布失败:', error);
        alert('发布失败，请重试');
    }
}

// 处理退出登录
async function handleLogout() {
    try {
        const response = await fetch('/api/users/logout', {
            method: 'POST'
        });
        
        if (response.ok) {
            state.currentUser = null;
            updateUserInterface();
            showPage('home');
        }
    } catch (error) {
        console.error('退出失败:', error);
    }
}

// 加载物品列表
async function loadItems() {
    try {
        const response = await fetch('/api/items');
        if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
                state.items = data.data;
                renderAllItems();
            }
        }
    } catch (error) {
        console.error('加载物品列表失败:', error);
    }
}

// 处理搜索
async function handleSearch() {
    const keyword = document.getElementById('searchInput').value.trim();
    
    try {
        const response = await fetch(`/api/items/search?keyword=${encodeURIComponent(keyword)}`);
        if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
                state.items = data.data;
                renderAllItems();
            }
        }
    } catch (error) {
        console.error('搜索失败:', error);
        alert('搜索失败，请重试');
    }
}

// 渲染物品列表
function renderAllItems() {
    // 渲染所有物品
    renderItems(document.getElementById('itemsList'), state.items);
    
    // 渲染寻物启事（只显示未认领的）
    const lostItems = state.items.filter(item => item.status === 'LOST');
    renderItems(document.getElementById('lostItemsList'), lostItems);
    
    // 渲染招领启事（只显示未认领和待确认的）
    const foundItems = state.items.filter(item => 
        item.status === 'FOUND' || item.status === 'PENDING_CLAIM'
    );
    renderItems(document.getElementById('foundItemsList'), foundItems);
}

function renderItems(container, items) {
    if (!container) return;
    
    container.innerHTML = items.map(item => `
        <div class="item-card" onclick="showItemDetail(${item.id})">
            <div class="item-image">
                ${item.image 
                    ? `<img src="${item.image}" alt="${item.name}" onerror="this.onerror=null; this.src='/images/no-image.png';">`
                    : `<div class="no-image">暂无图片</div>`
                }
            </div>
            <div class="item-content">
                <h3 class="item-title">${item.name}</h3>
                <p class="item-description">${item.description}</p>
                <div class="item-meta">
                    <span class="item-location">
                        <i class="fas fa-map-marker-alt"></i> ${item.location}
                    </span>
                    <span class="item-time">
                        <i class="far fa-clock"></i> ${formatDate(item.createTime)}
                    </span>
                </div>
                <div class="item-status ${item.status.toLowerCase()}">
                    ${getStatusText(item.status)}
                </div>
            </div>
        </div>
    `).join('');
}

// 添加获取状态文本的辅助函数
function getStatusText(status) {
    switch (status) {
        case 'LOST':
            return '寻物启事';
        case 'FOUND':
            return '招领启事';
        case 'PENDING_CLAIM':
            return '等待认领';
        case 'CLAIMED':
            return '已认领';
        default:
            return status;
    }
}

// 添加日期格式化函数
function formatDate(dateStr) {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
}

// 当前查看的物品ID
let currentItemId = null;

// 改showItemDetail函数，添加currentItemId的设置
async function showItemDetail(itemId) {
    try {
        currentItemId = itemId;
        const response = await fetch(`/api/items/${itemId}`);
        if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
                const item = data.data;
                
                // 更新详情页面内容
                document.getElementById('detailTitle').textContent = item.name;
                document.getElementById('detailDescription').textContent = item.description;
                document.getElementById('detailLocation').textContent = item.location;
                document.getElementById('detailTime').textContent = formatDate(item.createTime);
                document.getElementById('detailUser').textContent = item.user ? item.user.username : '匿名用户';
                
                // 更新状态标签
                const statusElem = document.getElementById('detailStatus');
                let statusText = getStatusText(item.status);
                statusElem.textContent = statusText;
                statusElem.className = `item-status ${item.status.toLowerCase()}`;
                
                // 更新图片
                const imageContainer = document.getElementById('detailImage');
                if (item.image) {
                    imageContainer.innerHTML = `<img src="${item.image}" alt="${item.name}" onerror="this.onerror=null; this.src='/images/no-image.png';">`;
                } else {
                    imageContainer.innerHTML = `<div class="no-image">暂无图片</div>`;
                }
                
                // 更新操作按钮
                const actionsContainer = document.getElementById('detailActions');
                actionsContainer.innerHTML = ''; // 清现有按钮

                // 获取认领记录
                const claimResponse = await fetch(`/api/items/${itemId}/claims`);
                const claimData = await claimResponse.json();
                const claims = claimData.code === 200 ? claimData.data : [];

                // 显示删除按钮（如果是物品发布者）
                if (state.currentUser && state.currentUser.id === item.userId) {
                    actionsContainer.innerHTML += `
                        <button class="btn btn-danger" onclick="deleteItem(${item.id})">
                            <i class="fas fa-trash"></i> 删除物品
                        </button>
                    `;
                }

                // 显示认领按钮（如果是招领启事且未被认领）
                if (item.status === 'FOUND' && !claims.length) {
                    if (state.currentUser) {
                        if (state.currentUser.id !== item.userId) {
                            actionsContainer.innerHTML += `
                                <button class="btn btn-claim" onclick="claimItem(${item.id})">
                                    <i class="fas fa-hand-holding"></i> 认领物品
                                </button>
                            `;
                        }
                    } else {
                        actionsContainer.innerHTML += `
                            <button class="btn btn-claim" onclick="showPage('login')">
                                <i class="fas fa-sign-in-alt"></i> 登录后认领
                            </button>
                        `;
                    }
                }

                // 显示认领信息（如果有）
                if (claims.length > 0) {
                    const claim = claims[0];
                    let statusText = '';
                    let statusClass = '';

                    switch (claim.status) {
                        case 'PENDING':
                            statusText = '等待确认';
                            statusClass = 'pending';
                            break;
                        case 'APPROVED':
                            statusText = '已认领';
                            statusClass = 'approved';
                            break;
                        case 'REJECTED':
                            statusText = '已拒绝';
                            statusClass = 'rejected';
                            break;
                    }

                    // 显示认领信息
                    actionsContainer.innerHTML += `
                        <div class="claim-info">
                            <div class="claim-status ${statusClass}">
                                <i class="fas fa-info-circle"></i>
                                ${statusText}
                            </div>
                            <div class="claim-details">
                                <div class="claim-row">
                                    <span class="claim-label">认领人：</span>
                                    <span class="claim-value">${claim.realName}</span>
                                </div>
                                <div class="claim-row">
                                    <span class="claim-label">学号：</span>
                                    <span class="claim-value">${claim.studentId}</span>
                                </div>
                                <div class="claim-row">
                                    <span class="claim-label">联系电话：</span>
                                    <span class="claim-value">${claim.phone}</span>
                                </div>
                                ${claim.description ? `
                                    <div class="claim-row">
                                        <span class="claim-label">认领说明：</span>
                                        <span class="claim-value">${claim.description}</span>
                                    </div>
                                ` : ''}
                                <div class="claim-row">
                                    <span class="claim-label">申请时间</span>
                                    <span class="claim-value">${formatDate(claim.createTime)}</span>
                                </div>
                            </div>
                            ${claim.status === 'PENDING' && state.currentUser && state.currentUser.id === item.userId ? `
                                <div class="claim-actions">
                                    <button class="btn btn-success" onclick="handleClaim(${claim.id}, 'APPROVED')">
                                        <i class="fas fa-check"></i> 同意
                                    </button>
                                    <button class="btn btn-danger" onclick="handleClaim(${claim.id}, 'REJECTED')">
                                        <i class="fas fa-times"></i> 拒绝
                                    </button>
                                </div>
                            ` : ''}
                        </div>
                    `;
                }
                
                // 加载评论
                await loadComments(itemId);
                
                // 显示详情页面
                showPage('detail');
            }
        }
    } catch (error) {
        console.error('加载物品详情失败:', error);
    }
}

// 提交评论
async function submitComment() {
    if (!state.currentUser) {
        alert('请先登录');
        showPage('login');
        return;
    }

    const content = document.getElementById('commentContent').value.trim();
    if (!content) {
        alert('请输入评论内容');
        return;
    }

    if (!currentItemId) {
        alert('系统错误');
        return;
    }

    try {
        const response = await fetch('/api/comments', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content: content,
                itemId: currentItemId
            })
        });

        const data = await response.json();
        if (data.code === 200) {
            // 清空评论框
            document.getElementById('commentContent').value = '';
            // 重新加载评论列表
            await loadComments(currentItemId);
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('发表评论失败:', error);
        alert('发表评论失败，请重试');
    }
}

// 删除评论
async function deleteComment(commentId) {
    if (!state.currentUser) {
        alert('请先登录');
        return;
    }

    // 直接使用中文字符串
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/comments/${commentId}`, {
            method: 'DELETE'
        });

        const data = await response.json();
        if (data.code === 200) {
            // 重新加载评论列表
            await loadComments(currentItemId);
        } else {
            alert(data.message || '删除失败');
        }
    } catch (error) {
        console.error('删除评论失败:', error);
        alert('删除评论失败，请重试');
    }
}

// 修改loadComments函数
async function loadComments(itemId) {
    try {
        const response = await fetch(`/api/comments?itemId=${itemId}`);
        if (response.ok) {
            const data = await response.json();
            if (data.code === 200) {
                const comments = data.data;
                const commentsList = document.getElementById('commentsList');
                
                if (comments && comments.length > 0) {
                    commentsList.innerHTML = comments.map(comment => `
                        <div class="comment-item">
                            <div class="comment-header">
                                <div class="comment-info">
                                    <span class="comment-user">${comment.user ? comment.user.username : '匿名用户'}</span>
                                    <span class="comment-time">${formatDate(comment.createTime)}</span>
                                </div>
                                ${state.currentUser && state.currentUser.id === comment.userId ? `
                                    <div class="comment-actions">
                                        <button class="btn btn-text btn-small" onclick="event.stopPropagation(); deleteComment(${comment.id})" title="删除评论">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                ` : ''}
                            </div>
                            <div class="comment-content">${comment.content}</div>
                        </div>
                    `).join('');
                } else {
                    commentsList.innerHTML = '<p class="no-comments">暂无评论</p>';
                }
            }
        }
    } catch (error) {
        console.error('加载评论失败:', error);
    }
}

// 修改认领物品的函数
async function claimItem(itemId) {
    if (!state.currentUser) {
        alert('请先登录');
        showPage('login');
        return;
    }

    // 显示认领表单
    const formHtml = `
        <div class="claim-form">
            <h3>认领信息</h3>
            <div class="form-group">
                <label>真实姓名</label>
                <input type="text" id="claimRealName" required>
            </div>
            <div class="form-group">
                <label>学号</label>
                <input type="text" id="claimStudentId" required>
            </div>
            <div class="form-group">
                <label>联系电话</label>
                <input type="tel" id="claimPhone" required>
            </div>
            <div class="form-group">
                <label>认领说明（选填）</label>
                <textarea id="claimDescription"></textarea>
            </div>
            <div class="form-actions">
                <button class="btn btn-text" onclick="closeClaimForm()">取消</button>
                <button class="btn btn-claim" onclick="submitClaim(${itemId})">确认认领</button>
            </div>
        </div>
    `;

    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.innerHTML = formHtml;
    document.body.appendChild(modal);
}

// 关闭认领表单
function closeClaimForm() {
    const modal = document.querySelector('.modal');
    if (modal) {
        modal.remove();
    }
}

// 提交认领信息
async function submitClaim(itemId) {
    const realName = document.getElementById('claimRealName').value.trim();
    const studentId = document.getElementById('claimStudentId').value.trim();
    const phone = document.getElementById('claimPhone').value.trim();
    const description = document.getElementById('claimDescription').value.trim();

    if (!realName) {
        alert('请填写真实姓名');
        return;
    }
    if (!studentId) {
        alert('请填写学号');
        return;
    }
    if (!phone) {
        alert('请填写联系电话');
        return;
    }

    try {
        const response = await fetch(`/api/items/${itemId}/claim`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                itemId: itemId,
                realName: realName,
                studentId: studentId,
                phone: phone,
                description: description
            })
        });

        const data = await response.json();
        if (data.code === 200) {
            alert('认领成功');
            closeClaimForm();
            // 重新加载物品详情
            await showItemDetail(itemId);
        } else {
            alert(data.message || '认领失败');
        }
    } catch (error) {
        console.error('认领失败:', error);
        alert('认领失败，请重试');
    }
}

// 添加处理认领申请的函数
async function handleClaim(claimId, status) {
    try {
        const response = await fetch(`/api/items/claims/${claimId}/handle?status=${status}`, {
            method: 'POST'
        });

        const data = await response.json();
        if (data.code === 200) {
            alert(status === 'APPROVED' ? '已同意认领申请' : '已拒绝认领申请');
            // 重新加载物品详情
            await showItemDetail(currentItemId);
        } else {
            alert(data.message || '处理失败');
        }
    } catch (error) {
        console.error('处理认领申请失败:', error);
        alert('处理失败，请重试');
    }
}

// 添加删除物品的函数
async function deleteItem(itemId) {
    if (!state.currentUser) {
        alert('请先登录');
        return;
    }

    if (!confirm('确定要删除这个物品吗？删除后无法恢复。')) {
        return;
    }

    try {
        const response = await fetch(`/api/items/${itemId}`, {
            method: 'DELETE'
        });

        const data = await response.json();
        if (data.code === 200) {
            alert('删除成功');
            // 重新加载物品列表并返回首页
            await loadItems();
            showPage('home');
        } else {
            alert(data.message || '删除失败');
        }
    } catch (error) {
        console.error('删除物品失败:', error);
        alert('删除失败，请重试');
    }
}

// 添加图片预览功能
function previewImage(input) {
    const preview = document.getElementById('imagePreview');
    const fileName = document.getElementById('fileName');
    
    if (input.files && input.files[0]) {
        const file = input.files[0];
        
        // 显示文件名
        fileName.textContent = file.name;
        
        // 预览图片
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.style.display = 'block';
            preview.innerHTML = `<img src="${e.target.result}" alt="预览图片">`;
        };
        reader.readAsDataURL(file);
    } else {
        fileName.textContent = '';
        preview.style.display = 'none';
        preview.innerHTML = '';
    }
} 